package com.smart.village.big.screen.controller.bigscreen;

import com.smart.village.big.screen.domain.MergedPathsResponse;
import com.smart.village.big.screen.domain.NewsCategory;
import com.smart.village.big.screen.service.AdminNewsCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping({"/api/news-categories"})
public class AdminNewsCategoryController {
    @Autowired
    private AdminNewsCategoryService adminNewsCategoryService;

    @GetMapping({"/merged-paths"})
    public ResponseEntity<List<NewsCategory>> getMergedPathsToRoot(@RequestParam("ids") String ids) {
        List<String> leafNodeIds = parseIds(ids);
        MergedPathsResponse response = this.adminNewsCategoryService.mergePathsToRoot(leafNodeIds);
        return ResponseEntity.ok(response.getTree());
    }

    @GetMapping({"/merged-paths/detail"})
    public ResponseEntity<MergedPathsResponse> getMergedPathsToRootDetail(@RequestParam("ids") String ids) {
        List<String> leafNodeIds = parseIds(ids);
        MergedPathsResponse response = this.adminNewsCategoryService.mergePathsToRoot(leafNodeIds);
        return ResponseEntity.ok(response);
    }

    private List<String> parseIds(String ids) {
        if (ids == null || ids.trim().isEmpty())
            throw new IllegalArgumentException("ids 参数不能为空");
        return (List<String>) Arrays.<String>stream(ids.split("[,\\s;]+"))
                .map(String::trim)
                .filter(id -> !id.isEmpty())
                .collect(Collectors.toList());
    }
}
